package cn.janescott.framework.druid;

import cn.janescott.framework.druid.properties.MonitorProperties;
import cn.janescott.framework.druid.servlet.MyStatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author scott
 * @date 2019/2/18
 */
@AutoConfigureBefore(DispatcherServletAutoConfiguration.class)
@Configuration
@ConditionalOnWebApplication(
        type = ConditionalOnWebApplication.Type.SERVLET
)
@EnableConfigurationProperties(MonitorProperties.class)
@ConditionalOnProperty(prefix = "druid.monitor", name = "monitor", havingValue = "true")
public class DruidMonitorConfiguration {

    @Resource
    private MonitorProperties properties;

    /**
     * stat
     */
    @Bean("statServlet")
    public ServletRegistrationBean druidStatViewServlet() {
        //注册servlet
        ServletRegistrationBean statServlet = new ServletRegistrationBean<>(new MyStatViewServlet(), properties.getPath());
        statServlet.setLoadOnStartup(1);
        statServlet.setName(properties.getServletName());
        //添加初始化参数 initParams
        //白名单(没有配置或者为空，则允许所有访问)
        if (StringUtils.hasText(properties.getAllow())) {
            statServlet.addInitParameter("allow", properties.getAllow());
        }
        /* 黑名单(同时存在时，deny优于allow) */
        if (StringUtils.hasText(properties.getDeny())) {
            statServlet.addInitParameter("deny", properties.getDeny());
        }
        /* 禁用HTML页面上的“Reset All”功能 */
        statServlet.addInitParameter("resetEnable", String.valueOf(properties.isResetEnable()));
        //登录用户名
        statServlet.addInitParameter("loginUsername", properties.getLoginUsername());
        //登录密码
        statServlet.addInitParameter("loginPassword", properties.getLoginPassword());
        //远程数据源  https://note.youdao.com/ynoteshare1/index.html?id=d9c15b09f9b462bf7bc5a7e29deb6e06&type=note#/
        /* statServlet.addInitParameter("jmxUrl", "service:jmx:rmi:///jndi/rmi://172.21.129.216:9003/jmxrmi"); */
        if (StringUtils.hasText(properties.getJmxUrl())) {
            statServlet.addInitParameter("jmxUrl", properties.getJmxUrl());
            if (StringUtils.hasText(properties.getJmxUsername())) {
                statServlet.addInitParameter("jmxUsername", properties.getJmxUsername());
            }
            if (StringUtils.hasText(properties.getJmxPassword())) {
                statServlet.addInitParameter("jmxPassword", properties.getJmxPassword());
            }
        }
        /* "service:jmx:rmi:///jndi/rmi://172.21.129.216:9003/jmxrmi,service:jmx:rmi:///jndi/rmi://172.21.129.216:9004/jmxrmi" */
        if (!CollectionUtils.isEmpty(properties.getJmxUrls())) {
            statServlet.addInitParameter("jmxUrls", properties.getJmxUrls().stream().reduce((o1, o2) -> o1 + "," + o2).orElse(null));
            if (!CollectionUtils.isEmpty(properties.getJmxDruidNames())) {
                statServlet.addInitParameter("jmxDruidNames", properties.getJmxDruidNames().stream().reduce((o1, o2) -> o1 + "," + o2).orElse(null));
            }
            if (!CollectionUtils.isEmpty(properties.getJmxUserNames())) {
                statServlet.addInitParameter("jmxUserNames", properties.getJmxUserNames().stream().reduce((o1, o2) -> o1 + "," + o2).orElse(null));
            }
            if (!CollectionUtils.isEmpty(properties.getJmxPassWords())) {
                statServlet.addInitParameter("jmxPassWords", properties.getJmxPassWords().stream().reduce((o1, o2) -> o1 + "," + o2).orElse(null));
            }
        }
        /* 初始化检查jmx连接 */
        statServlet.addInitParameter("jmxInitialCheck", String.valueOf(properties.isInitialCheck()));
        /* 检查失败，是否启动失败 */
        statServlet.addInitParameter("jmxFailedOnCheck", String.valueOf(properties.isFailedOnCheck()));
        return statServlet;
    }

    /**
     * filter
     */
    @Bean("druidFilter")
    public FilterRegistrationBean druidFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(new WebStatFilter());
        filterRegistrationBean.setName(properties.getFilterName());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns(properties.getPattern());
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", properties.getExclusions() + "," + properties.getPath());
        return filterRegistrationBean;
    }

}
